<?php 
/**
 * NOTICE OF LICENSE
 *
 * This source file is subject to the  Academic Free License (AFL 3.0)
 * that is available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to support@zprofess.com so we can send you a copy immediately.
 *
 * @category   	Prestashop module
 * @package		Review & Rating Synthesis
 * @version 	1.0.2
 * @author 		Rukan <rukanhitokiri@zprofess.com>
 * @copyright   Copyright (c) 2012 ZPROFESS. (http://www.zprofess.com)
 * @license    	http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */

if (!defined('_CAN_LOAD_FILES_'))
    exit;
include_once(dirname(__FILE__).'/classes/ZCustomerBadges.php');
class ReviewRatingSynthesis extends Module
{	
	const INSTALL_SQL_FILE = 'sql/install.sql';
		
	function __construct()
	{
		global $smarty ;
		$this->name = 'reviewratingsynthesis';	
		$this->version = '1.4.0';
		$this->tab = 'front_office_features';
		$this->author = 'Zprofess.com';
		
		parent::__construct();		

		$this->displayName = $this->l('Review & Rating Synthesis');	
		$this->description = $this->l('Allow users to post Review & Rating about a product');
		$this->confirmUninstall = $this->l('Are you sure you want to delete your details?');
		$smarty->allow_php_tag = true;
		
		include_once(_PS_MODULE_DIR_.$this->name.'/classes/ZprofessConfigure.php');
	}
	
	/******************************
	 * BackOffice & Configuration *
	 ******************************/
	
	// Provides the interface between our module and the Back Office.
	public function getContent() 
	{	
		$this->_html .= '<h2>'.$this->displayName.'</h2>';
		$configure = new ZprofessConfigure();
		$configure->postProcess();
		$this->_html .= $configure->displayForm();
		return $this->_html;
	}
	
	/***************
	 * FrontOffice *
	 ***************/
	
	private function _sendMail($review)
	{
		$emailTemplate 		= Configuration::get('ZPRO_EMAIL_TEMPLATE');
		$emailNotification 	= Configuration::get('ZPRO_EMAIL_NOTIFICATION');
		$emailSubject 		= Configuration::get('ZPRO_EMAIL_SUBJECT');
		$templateVariables = array(
			'{product_name}' 	=> ZProductReview::getNameProductById($review->id_product),
			'{email}' 			=> $review->email,
			'{customer_name}'	=> $review->customer_name,
			'{content}' 		=> $review->content
		);
		$path = _PS_ROOT_DIR_."/modules/reviewratingsynthesis/email/";
		foreach ($templateVariables as $templateVariable=>$value)
			$emailTemplate = preg_replace ("/" . preg_quote($templateVariable) . "/", $value, $emailTemplate);
		$varsTpl = array('{content}' 		=> $emailTemplate,
						 '{product_name}'	=> ZProductReview::getNameProductById($review->id_product));
		@Mail::Send('1', 'sendAdmin', 'New Review and Rating for '.$templateVariables['{product_name}'] , $varsTpl, $emailNotification ,$emailSubject, NULL, NULL, NULL, NULL, $path, true);
	}
	
	/**
	 * front Office Post Process
	 */
	private function _frontOfficePostProcess()
	{
		global $cookie, $smarty;
		
		$allowGuests = (int)Configuration::get('ZPRO_ALLOW_GUESTS');
		if (Tools::isSubmit('submitReview') AND ($cookie->id_customer OR $allowGuests)) {
			$id_guest = $cookie->id_customer ? false : (int)$cookie->id_guest;	
			// Get last product comment by customer
			$customerReview = ZProductreview::getReviewByCustomer((int)Tools::getValue('id_product'), (int)$cookie->id_customer, (int)$id_guest, true);
			
			if (!$customerReview OR ($customerReview AND (strtotime($customerReview['date_add']) + Configuration::get('ZPRO_MINIMAL_TIME')) < time())) {
				// Validating form fields
				if ($id_guest AND !Tools::getValue('customer_name'))
					$this->_errors[] = Tools::displayError('Please fill your name.');
				if ($id_guest AND Tools::getValue('email') AND !Validate::isEmail(Tools::getValue('email'))) 
					$this->_errors[] = Tools::displayError('Invalid e-mail address.');
				if (!Tools::getValue('title'))
					$this->_errors[] = Tools::displayError('Please fill title.');
				if (!Tools::getValue('content'))
					$this->_errors[] = Tools::displayError('Review text is required.');

				// check captcha
				if (Configuration::get('ZPRO_ENABLE_CAPTCHA')) {				
					if (!$this->_errors) {
						require_once dirname(__FILE__) . '/lib/securimage/securimage.php';
						$securimage = new Securimage();
					  
						if ($securimage->check(Tools::getValue('captcha')) == false) {
							$this->_errors[] = 'Incorrect security code entered<br />';
						}
					}
				}
					
				if ($this->_errors) {				
					$smarty->assign('errors', $this->_errors);
					return;
				}
				
				if($id_guest) {
					$email = pSQL(Tools::getValue('email'));
					$customer_name = pSQL(Tools::getValue('customer_name'));
				} else {
					$email = $cookie->email;
					$customer_name = $cookie->customer_firstname.' '.$cookie->customer_lastname;
				}

				$review = new ZProductreview();
				$review->id_product 	= (int)$_GET['id_product'];
				$review->id_customer	= (int)$cookie->id_customer;
				$review->id_guest 		= (int)$id_guest;
				$review->customer_name 	= $customer_name;
				$review->email 			= $email;
				$review->website 		= pSQL(Tools::getValue('website'));
				$review->title 			= pSQL(Tools::getValue('title'));
				$review->content 		= strip_tags(Tools::getValue('content'));
				$review->status 		= 1; /*pending*/
				$review->save();
		
				for ($i = 1, $rating = 0; isset($_POST['score_'.$i]) === true; ++$i) {
					$crating = (int)Tools::getValue('score_'.$i);
					$rating += $crating;
					$review->addGrade((int)Tools::getValue('id_zproduct_criterion_'.$i), $crating);
				}
				if (($i - 1) > 0)
					$review->rating = ($rating / ($i - 1));
				if (!$review->save())
					$smarty->assign('confirmation', $this->l('An error occurred while saving your review.'));
				else {
					if (Configuration::get('ZPRO_ENABLE_EMAIL_NOTIFICATION'))
						$this->_sendMail($review);
					
					$validate = (int)(Configuration::get('ZPRO_VALIDATED_BY_EMPLOYEE'));
					$smarty->assign('confirmation', $validate ? $this->l('Reviews posted. You wait we confirm!') : $this->l('Reviews posted.'));
				}
			} else {
				$errors = $this->l('You should wait').' '.Configuration::get('ZPRO_MINIMAL_TIME').' '.$this->l('seconds before posting a new review');
				$smarty->assign('confirmation', $errors);
			}
		}
		if (Tools::isSubmit('submitReviewEdit') AND $cookie->id_customer) {
			$id_zproduct_review =  Tools::getValue('id_zproduct_review_edit');
			$content = Tools::getValue('content_edit');
			
			$content = pSQL ($content);
			$text = Tools::getValue('text_edit');
			$text = pSQL ($text);
			$review = new ZProductreview($id_zproduct_review);
			$validate = (int)(Configuration::get('ZPRO_VALIDATED_BY_EMPLOYEE'));
			
			for ($i = 1, $rating = 0; isset($_POST['edit_score_'.$i]) === true; ++$i) {
				$crating = (int)Tools::getValue('edit_score_'.$i);
				$rating += $crating;
				$review->editGrade((int)Tools::getValue('id_zproduct_criterion_'.$i), $crating);
			}
			if (($i - 1) > 0)
				$rating = ($rating / ($i - 1));
			
			if (Db::getInstance(_PS_USE_SQL_SLAVE_)->Execute('
				UPDATE `'._DB_PREFIX_.'zproduct_review` SET `content`="'.$content.'" , `status`=1,`title`="'.$text.'",`rating`='.$rating.'
				WHERE (`id_zproduct_review`='.$id_zproduct_review.')
			')) {
				$smarty->assign('confirmation', $validate ? $this->l('Reviews edit complete. You wait we confirm!') : $this->l('Reviews edit complete.'));
			}
			else 
				$smarty->assign('confirmation',$this->l('Reviews not edit.'));
		}
	}
	
	public function hookHeader()
	{
		Tools::addCSS($this->_path.'css/style.css', 'all');
		Tools::addJS($this->_path.'js/ajax.js');
		Tools::addJS($this->_path.'js/reviewratingsynthesis.js');
		//by xuanhoapro
		Tools::addJS($this->_path.'js/jquery-ui-1.8.10.custom.min.js');
		Tools::addCSS($this->_path.'css/jquery-ui-1.8.17.custom.css', 'all');
		Tools::addJS($this->_path.'js/add.register.js');
	}
	
	public function hookTop($params)
	{
		require_once(dirname(__FILE__).'/classes/ZProductCriterion.php');
		require_once(dirname(__FILE__).'/classes/ZProductReview.php');

		global $smarty, $cookie;
		
		if (isset($_POST['alias_custommer']) && isset($_POST['alias_active']) && !empty($_POST['alias_custommer'])) {
			$idCustomer = Db::getInstance()->getValue('
							SELECT `id_custommers` FROM `'._DB_PREFIX_.'zalias_custommers`
								WHERE `id_custommers` ='.(int)$cookie->id_customer);
			if($idCustomer) {
				Db::getInstance()->Execute('
				UPDATE `'._DB_PREFIX_.'zalias_custommers`
					SET `alias` = "'.$_POST['alias_custommer'].'", active = '.$_POST['alias_active'].' 
						WHERE `id_custommers` ='.(int)$cookie->id_customer);
			} else {
				Db::getInstance()->Execute('
				INSERT INTO `'._DB_PREFIX_.'zalias_custommers`
					VALUES (\''.(int)$cookie->id_customer.'\', \''.$_POST['alias_custommer'].'\', \''.$_POST['alias_active'].'\')');
			}
		}
		
		$this->_frontOfficePostProcess();
		ZprofessConfigure::getRatingConfig();
		
		return ($this->display(__FILE__, 'themes/top.tpl'));
	}
	
	public function hookExtraLeft($params) 
	{
		if(Configuration::get('ZPRO_HOOK_RATING') == 2) {
			return $this->hookProductFooter($params, 2);
		}
	}
	
	public function hookProductActions($params) 
	{
		if(Configuration::get('ZPRO_HOOK_RATING') == 1) {
			return $this->hookProductFooter($params, 1);
		}
	}
	
	public function hookExtraRight($params) 
	{
		if (Configuration::get('ZPRO_FB_SHARE')) {
			return ($this->display(__FILE__, 'themes/fb-share.tpl'));
		}
	}
	
	public function hookProductFooter($params, $hookOther = false)
	{
		global $smarty;
		$smarty->assign('nbReviews', (int)ZProductReview::getReviewNumber((int)Tools::getValue('id_product')));
		if(Configuration::get('ZPRO_HOOK_RATING') == 4 || $hookOther) {
			if(!Configuration::get('ZPRO_ONLY_REVIEW')) {
				global $smarty, $cookie;
				
				// averages rating for each criterion
				$averages = ZProductReview::getAveragesByProduct((int)Tools::getValue('id_product'), (int)$cookie->id_lang);
		    	$averageTotal = 0;
				foreach ($averages AS $average)
					$averageTotal += (float)($average);
				$averageTotal = count($averages) ? ($averageTotal / count($averages)) : 0;
				$averageTotal = round($averageTotal, 1);
				
				$smarty->assign('criterions', ZProductCriterion::getCriterionByProduct((int)Tools::getValue('id_product'), (int)$cookie->id_lang));
				$smarty->assign(array(
		    		'averages' 				=> $averages,
		    		'averageTotal' 			=> $averageTotal,
				    'zproNumber'			=> Configuration::get('ZPRO_NUMBER'),
					'configRating' 			=> ZprofessConfigure::$configRating,
		    	));
				
				return ($this->display(__FILE__, 'themes/averages.tpl'));
			}
		}
	}
	
	
	public function hookProductTab($params)
    {
    	global $smarty;
    	$smarty->assign('nbReviews', (int)ZProductReview::getReviewNumber((int)Tools::getValue('id_product')));
    	return ($this->display(__FILE__, 'themes/tab.tpl'));
    }
    
    public function hookProductTabContent($params)
    {
    	global $smarty, $cookie;
    	
    	$id_guest = $cookie->id_customer ? false : (int)$cookie->id_guest;
    	// Get last product comment by customer
		$customerReview = ZProductReview::getReviewByCustomer((int)Tools::getValue('id_product'), (int)$cookie->id_customer, (int)$id_guest, true);
		$customerBadges = ZCustomerBadges::getCustomerByBadges((int)$cookie->id_lang);
		
		$controller = new FrontController();
		$nbReviews = (int)ZProductReview::getReviewNumber((int)Tools::getValue('id_product'));
		$controller->pagination((int)$nbReviews);
		
		$reviews = ZProductReview::getReviewByProduct((int)Tools::getValue('id_product'), Tools::getValue('p'), $controller->n);
		$i=0;
		$tmp = '';
		foreach ($reviews AS $review){
			foreach ($customerBadges AS $customer){
				$arrCustomer = explode(',', $customer['id_zcustomer']);
				if(in_array($review['id_customer'], $arrCustomer)){
					$tmp .= ($tmp =='' ? '' : '</span><span class="new">').$customer['name'];
				}
			}
			$reviews[$i]['badges'] = $tmp;
			$tmp = '';
			$i++;
		}
		
		$smarty->assign('criterions', ZProductCriterion::getCriterionByProduct((int)Tools::getValue('id_product'), (int)$cookie->id_lang));
    	$smarty->assign(array(
    	 	'too_early' 			=> ($customerReview AND (strtotime($customerReview['date_add']) + Configuration::get('ZPRO_MINIMAL_TIME')) > time()),
    		'delay' 				=> Configuration::get('ZPRO_MINIMAL_TIME'),
    		'allow_guests' 			=> (int)Configuration::get('ZPRO_ALLOW_GUESTS'),
    		'reviews' 				=> $reviews,
    		'configRating' 			=> ZprofessConfigure::$configRating,
    		'enable_email' 			=> (int)Configuration::get('ZPRO_ENABLE_EMAIL'),
    		'enable_website' 		=> (int)Configuration::get('ZPRO_ENABLE_WEBSITE'),
    		'display_email' 		=> (int)Configuration::get('ZPRO_DISPLAY_EMAIL'),
    		'display_website' 		=> (int)Configuration::get('ZPRO_DISPLAY_WEBSITE'),
    		'display_title' 		=> (int)Configuration::get('ZPRO_DISPLAY_TITLE'),
    		'only_review' 			=> (int)Configuration::get('ZPRO_ONLY_REVIEW'),
    		'enable_captcha' 		=> (int)Configuration::get('ZPRO_ENABLE_CAPTCHA'),
    		'enable_vote' 			=> (int)Configuration::get('ZPRO_ENABLE_VOTE'),
    		'pagination_dir'		=> dirname(__FILE__) . '/themes/pagination.tpl',
    	));
    	
    	$p = (int)Tools::getValue('p'); $n = (int)Tools::getValue('n');
    	if($p)
    		$smarty->assign('param_p', $p);
        if($n)
    		$smarty->assign('param_n', $n);
    		
		$smarty->assign('id_customer', $cookie->id_customer);
		
		// alias
		if(!$id_guest) {
			$alias = Db::getInstance()->getValue('
					SELECT `alias` FROM `'._DB_PREFIX_.'zalias_custommers`
					WHERE active = 2 AND `id_custommers` ='.(int)$cookie->id_customer);
			if($alias) 
				$customer_name = $alias . ' (alias name)';
			else
				$customer_name = $cookie->customer_firstname.' '.$cookie->customer_lastname . ' (real name)';
		}
		
		$smarty->assign('customer_name', $customer_name);
		
    	return $this->display(__FILE__, '/themes/reviews.tpl');
    }
    
	public function hookExtraProductComparison($params)
	{
		if(!Configuration::get('ZPRO_ONLY_REVIEW')) {
			global $smarty, $cookie;
		
			$list_criterion = array();
			$list_product_grades = array();
			//$list_product_average = array();
			
			foreach ($params['list_ids_product'] AS $id_product)
			{
				$averages = ZProductReview::getAveragesByProduct((int)$id_product, (int)$cookie->id_lang);
				$criterions = ZProductCriterion::getCriterionByProduct((int)$id_product, (int)$cookie->id_lang);			
				
				$grade_total = 0;
				if (sizeof($averages) > 0) {
					foreach ($criterions AS $criterion) {					
						$list_product_grades[$criterion['id_zproduct_criterion']][$id_product] = $averages[$criterion['id_zproduct_criterion']];
						$grade_total += (float)$averages[$criterion['id_zproduct_criterion']];
						
						if (!array_key_exists($criterion['id_zproduct_criterion'], $list_criterion))
							$list_criterion[$criterion['id_zproduct_criterion']] = $criterion['name'];
					}
					$list_product_average[$id_product] = $grade_total / count($criterions);
				}
			}
	
			if (sizeof($list_criterion) < 1) 
				return false;
				
			$smarty->assign(array(
				'list_ids_product' 		=> $params['list_ids_product'], 
				'product_grades' 		=> $list_product_grades,
				'criteria' 				=> $list_criterion,
				'configRating' 			=> ZprofessConfigure::$configRating,
				'list_product_average' => $list_product_average,
			));
	
			return $this->display(__FILE__,'/themes/products-comparison.tpl');
		}
	}
	
	public function hookLeftColumn($params)
	{
		if(Configuration::get('ZPRO_HOOK_LATEST_REVIEWS') == 2 || Configuration::get('ZPRO_HOOK_VOTE_MOST') == 2) {
			return $this->hookHome($params, 2);
		}
	}
	
	public function hookRightColumn($params)
	{
		if (Configuration::get('ZPRO_HOOK_LATEST_REVIEWS') == 3 || Configuration::get('ZPRO_HOOK_VOTE_MOST') == 3) {
			return $this->hookHome($params, 3);
		}
	}
	
	private function _getLatestReviews($params) 
	{
		$latestReviews = ZProductReview::getLatestReviews();
		
		$productIdArray = array();
		foreach ($latestReviews as $latestReview) {
			$productIdArray[] = $latestReview['id_product'];
		}
		$productIds = implode(',', $productIdArray);
		
		if ($productIds) {
			$productsImages = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
					SELECT i.id_image, p.id_product, il.legend, pl.name, pl.link_rewrite, cl.link_rewrite AS category_rewrite
					FROM '._DB_PREFIX_.'product p
					LEFT JOIN '._DB_PREFIX_.'product_lang pl ON (pl.id_product = p.id_product)
					LEFT JOIN '._DB_PREFIX_.'image i ON (i.id_product = p.id_product AND i.cover = 1)
					LEFT JOIN '._DB_PREFIX_.'image_lang il ON (il.id_image = i.id_image)
					LEFT JOIN '._DB_PREFIX_.'category_lang cl ON (cl.id_category = p.id_category_default)
					WHERE p.id_product IN ('.$productIds.')
					AND pl.id_lang = '.(int)($params['cookie']->id_lang).'
					AND cl.id_lang = '.(int)($params['cookie']->id_lang).'
					GROUP BY id_image'
			);
		
			for($i=0; $i<count($latestReviews); $i++) {
				for($j=0; $j<count($productsImages); $j++) {
					if($productsImages[$j]['id_product'] == $latestReviews[$i]['id_product']) {
						$latestReviews[$i]['cover'] = (int)($productsImages[$j]['id_product']).'-'.(int)($productsImages[$j]['id_image']);
						$latestReviews[$i]['legend'] = $productsImages[$j]['legend'];
						$latestReviews[$i]['name'] = $productsImages[$j]['name'];
						$latestReviews[$i]['link_rewrite'] = $productsImages[$j]['link_rewrite'];
						$latestReviews[$i]['category_rewrite'] = $productsImages[$j]['category_rewrite'];
						break;
					}
				}
			}
		}
		return $latestReviews;
	}
	
	private function _getLikeMost($params)
	{
		$latestVote = ZProductReview::getLikeMost();
		
		$productIdArray = array();
		foreach ($latestVote as $vote) {
			$productIdArray[] = $vote['id_product'];
		}
		$productIds = implode(',', $productIdArray);
		
		if ($productIds) {
			$productsImages = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
					SELECT i.id_image, p.id_product, il.legend, pl.name, pl.link_rewrite, cl.link_rewrite AS category_rewrite
					FROM '._DB_PREFIX_.'product p
					LEFT JOIN '._DB_PREFIX_.'product_lang pl ON (pl.id_product = p.id_product)
					LEFT JOIN '._DB_PREFIX_.'image i ON (i.id_product = p.id_product AND i.cover = 1)
					LEFT JOIN '._DB_PREFIX_.'image_lang il ON (il.id_image = i.id_image)
					LEFT JOIN '._DB_PREFIX_.'category_lang cl ON (cl.id_category = p.id_category_default)
					WHERE p.id_product IN ('.$productIds.')
					AND pl.id_lang = '.(int)($params['cookie']->id_lang).'
					AND cl.id_lang = '.(int)($params['cookie']->id_lang).'
					GROUP BY id_image'
			);
		
			for($i=0; $i<count($latestVote); $i++) {
				for($j=0; $j<count($productsImages); $j++) {
					if($productsImages[$j]['id_product'] == $latestVote[$i]['id_product']) {
						$latestVote[$i]['cover'] = (int)($productsImages[$j]['id_product']).'-'.(int)($productsImages[$j]['id_image']);
						$latestVote[$i]['legend'] = $productsImages[$j]['legend'];
						$latestVote[$i]['name'] = $productsImages[$j]['name'];
						$latestVote[$i]['link_rewrite'] = $productsImages[$j]['link_rewrite'];
						$latestVote[$i]['category_rewrite'] = $productsImages[$j]['category_rewrite'];
						break;
					}
				}
			}
		}
		return $latestVote;
	}
	
	public function hookHome($params, $hookOther = false)
	{	
		global $smarty;
		
		if (Configuration::get('ZPRO_HOOK_LATEST_REVIEWS') == 1 AND !$hookOther) {
			$smarty->assign('latestReviews', $this->_getLatestReviews($params));
			$smarty->assign(array(
					'mediumSize' 			=> Image::getSize('medium'),
					'zproNumber'			=> Configuration::get('ZPRO_NUMBER'),
					'configRating' 			=> ZprofessConfigure::$configRating,
					'only_review' 			=> (int)Configuration::get('ZPRO_ONLY_REVIEW'),
					'display_email' 		=> (int)Configuration::get('ZPRO_DISPLAY_EMAIL'),
					'display_website' 		=> (int)Configuration::get('ZPRO_DISPLAY_WEBSITE'),
					'display_title' 		=> (int)Configuration::get('ZPRO_DISPLAY_TITLE'),
			));
			
			return $this->display(__FILE__,'/themes/latest-reviews-home.tpl');
		} 
		if ($hookOther) {
			if(Configuration::get('ZPRO_HOOK_LATEST_REVIEWS') == $hookOther) {
				$smarty->assign('latestReviews', $this->_getLatestReviews($params));
			} else {
				$smarty->assign('latestReviews', array());
			}
				
			if(Configuration::get('ZPRO_HOOK_VOTE_MOST') == $hookOther) {
				$smarty->assign('latestVote', $this->_getLikeMost($params));
			} else {
				$smarty->assign('latestVote', array());
			}
				
			$smarty->assign(array(
				'mediumSize' 			=> Image::getSize('medium'), 
				'zproNumber'			=> Configuration::get('ZPRO_NUMBER'),
				'configRating' 			=> ZprofessConfigure::$configRating,
				'only_review' 			=> (int)Configuration::get('ZPRO_ONLY_REVIEW'),
			    'display_email' 		=> (int)Configuration::get('ZPRO_DISPLAY_EMAIL'),
    			'display_website' 		=> (int)Configuration::get('ZPRO_DISPLAY_WEBSITE'),
    			'display_title' 		=> (int)Configuration::get('ZPRO_DISPLAY_TITLE'),
			));
			
			return $this->display(__FILE__,'/themes/latest-reviews-vote.tpl');
		}
	}
	//by xuanhoapro
	function hookCreateAccount ($params)
	{
		global $cookie;
		if ((Tools::isSubmit('submitAccount') OR Tools::isSubmit('submitGuestAccount'))){
			$field = array('id_custommers' => (int)$cookie->id_customer,
						    'alias' => $_POST['alias_custommer'],
							'active' => 1);
			if(!Db::getInstance()->AutoExecute(_DB_PREFIX_.'zalias_custommers', $field, 'INSERT'))
				die('error create alias');
		}
	}
	// end by xuanhoapro
	/***********************
	 * Install & UnInstall *
	 ***********************/
	
	/**
	 * Install
	 *
	 * @return boolean
	 */
	function install()
	{
		/*Install sql*/
		if ((!file_exists(dirname(__FILE__).'/'.self::INSTALL_SQL_FILE)) 
		   || (!$sql = file_get_contents(dirname(__FILE__).'/'.self::INSTALL_SQL_FILE)))
				return false;
		$sql = str_replace(array('PREFIX_', 'ENGINE_TYPE'), array(_DB_PREFIX_, _MYSQL_ENGINE_), $sql);
		$sql = preg_split("/;\s*[\r\n]+/", $sql);
		foreach ($sql AS $query)
			if (!Db::getInstance()->Execute(trim($query)))
				return false;
		/*Add Tab*/
		if (!$this->_addAdminTab())
			return false;
		/* Version value*/
		if (!Configuration::updateValue('ZPRO_REVIEWS_VERSION', '1.0'))
			return false;
		/* Configuration value*/
		if (!Configuration::updateValue('ZPRO_MINIMAL_TIME', 30)
		 	OR !Configuration::updateValue('ZPRO_ALLOW_GUESTS', 0)
		 	OR !Configuration::updateValue('ZPRO_VALIDATED_BY_EMPLOYEE', 1)
		 	OR !Configuration::updateValue('ZPRO_ONLY_REVIEW', 0)
		 	OR !Configuration::updateValue('ZPRO_HOOK_RATING', 0)
		 	OR !Configuration::updateValue('ZPRO_HOOK_LATEST_REVIEWS', 0)
		 	OR !Configuration::updateValue('ZPRO_NUMBER_LATEST_REVIEWS', 4)
		 	OR !Configuration::updateValue('ZPRO_ENABLE_VOTE', 1)
		 	OR !Configuration::updateValue('ZPRO_HOOK_VOTE_MOST', 0)
		 	OR !Configuration::updateValue('ZPRO_NUMBER_VOTE_MOST', 4)
		 	OR !Configuration::updateValue('ZPRO_FB_SHARE', 0))
				return false;
		/* Configuration rating value*/
		$this->_path = __PS_BASE_URI__.'modules/reviewratingsynthesis/';
		if (!Configuration::updateValue('ZPRO_WIDTH', '')
			OR !Configuration::updateValue('ZPRO_RATING_STYLE', 1)
			OR !Configuration::updateValue('ZPRO_CANCEL', 0)
			OR !Configuration::updateValue('ZPRO_CANCEL_HINT', 'cancel this rating!')
			OR !Configuration::updateValue('ZPRO_CANCEL_OFF', 'raty/cancel-off.png')
			OR !Configuration::updateValue('ZPRO_CANCEL_ON', 'raty/cancel-on.png')
			OR !Configuration::updateValue('ZPRO_CANCEL_PLACE', 1)
			OR !Configuration::updateValue('ZPRO_HALF', 0)
			OR !Configuration::updateValue('ZPRO_HINT_LIST', 'bad, poor, regular, good, gorgeous')
			OR !Configuration::updateValue('ZPRO_NO_RATED_MSG', 'not rated yet')
			OR !Configuration::updateValue('ZPRO_NUMBER', 5)
			OR !Configuration::updateValue('ZPRO_PATH', $this->_path.'img/')
			OR !Configuration::updateValue('ZPRO_ICON_RANGE', '[]')
			OR !Configuration::updateValue('ZPRO_STAR_HALF', 'raty/star-half.png')
			OR !Configuration::updateValue('ZPRO_STAR_OFF', 'raty/star-off.png')
			OR !Configuration::updateValue('ZPRO_STAR_ON', 'raty/star-on.png')
			OR !Configuration::updateValue('ZPRO_START', 3))
				return false;
		/* Configuration captcha value*/
		if (!Configuration::updateValue('ZPRO_ENABLE_CAPTCHA', 1)
			OR !Configuration::updateValue('ZPRO_HEIGHT_IMG', 55)
		 	OR !Configuration::updateValue('ZPRO_WIDTH_IMG', 190)
		 	OR !Configuration::updateValue('ZPRO_BG_COLOR', '#EAEAEA')
		 	OR !Configuration::updateValue('ZPRO_TEXT_COLOR', '#0099CC')
		 	OR !Configuration::updateValue('ZPRO_LINE_COLOR', '#3B3B3B')
		 	OR !Configuration::updateValue('ZPRO_CODE_LENGTH', 6)
		 	OR !Configuration::updateValue('ZPRO_NUMBER_LINE', 6)
		 	OR !Configuration::updateValue('ZPRO_SIGNATURE_COLOR', '#000000'))
				return false;
		/* Configuration reviews value*/
		if (!Configuration::updateValue('ZPRO_DISPLAY_TITLE', 1))
				return false;
		/* Configuration email value*/
		if (!Configuration::updateValue('ZPRO_ENABLE_EMAIL_NOTIFICATION', 0)
			OR !Configuration::updateValue('ZPRO_EMAIL_NOTIFICATION', '')
		 	OR !Configuration::updateValue('ZPRO_EMAIL_SUBJECT', '')
		 	OR !Configuration::updateValue('ZPRO_EMAIL_TEMPLATE', ''))
				return false;
		/*Core Install & Register Hook*/
		if (!parent::install()
			OR !$this->registerHook('header')
		 	OR !$this->registerHook('top') 
		 	OR !$this->registerHook('leftColumn')
		 	OR !$this->registerHook('rightColumn')
		 	OR !$this->registerHook('home')
		 	OR !$this->registerHook('extraProductComparison')
		 	OR !$this->registerHook('productTab') 
		 	OR !$this->registerHook('productTabContent')
		 	OR !$this->registerHook('productActions') 
		 	OR !$this->registerHook('productFooter')
		 	OR !$this->registerHook('extraLeft') 
		 	OR !$this->registerHook('CreateAccount')
		 	OR !$this->registerHook('extraRight'))
		 	
				return false;
		return true;
	}
	
	/**
	 * Add new tab in administration
	 * 	 
	 * @return boolean
	 */
  	private function _addAdminTab()
  	{
		$idTabParent = Tab::getIdFromClassName('AdminCatalog');
    	$languages = Language::getlanguages(false);	/*All languages id*/
     	foreach ($languages as $langs) {
        	$tabNames[$langs['id_lang']] = 'Review & Rating Synthesis';
    	}
    	$tab = new Tab();
		$tab->module = $this->name;
    	$tab->name = $tabNames;
    	$tab->class_name = 'AdminZProductReviewRating';
    	$tab->id_parent = $idTabParent;
    	if (!$tab->save())
      		return false;
    	return true;
	}
	
	/**
	 * UnInstall
	 * 
	 * @return boolean
	 */
	public function uninstall()
	{  
		if (!parent::uninstall())
			return false;
		/*Remove tab*/
		if (!$this->_removeAdminTab())
			return false;
		/* Delete Version value*/
		if (!Configuration::deleteByName('ZPRO_REVIEWS_VERSION'))
			return false;
		/*Delete Configuration value*/
		if (!Configuration::deleteByName('ZPRO_MINIMAL_TIME') 
		 	OR !Configuration::deleteByName('ZPRO_ALLOW_GUESTS') 
		 	OR !Configuration::deleteByName('ZPRO_VALIDATED_BY_EMPLOYEE')
		 	OR !Configuration::deleteByName('ZPRO_ONLY_REVIEW')
		 	OR !Configuration::deleteByName('ZPRO_HOOK_RATING')
		 	OR !Configuration::deleteByName('ZPRO_HOOK_LATEST_REVIEWS')
		 	OR !Configuration::deleteByName('ZPRO_NUMBER_LATEST_REVIEWS')
		 	OR !Configuration::deleteByName('ZPRO_ENABLE_VOTE')
		 	OR !Configuration::deleteByName('ZPRO_HOOK_VOTE_MOST')
		 	OR !Configuration::deleteByName('ZPRO_NUMBER_VOTE_MOST')
		 	OR !Configuration::deleteByName('ZPRO_FB_SHARE'))
				return false;
		/*Delete Configuration value*/
		if (!Configuration::deleteByName('ZPRO_WIDTH')
			OR !Configuration::deleteByName('ZPRO_CANCEL')
			OR !Configuration::deleteByName('ZPRO_CANCEL_HINT')
			OR !Configuration::deleteByName('ZPRO_CANCEL_OFF')
			OR !Configuration::deleteByName('ZPRO_CANCEL_ON')
			OR !Configuration::deleteByName('ZPRO_CANCEL_PLACE')
			OR !Configuration::deleteByName('ZPRO_HALF')
			OR !Configuration::deleteByName('ZPRO_HINT_LIST')
			OR !Configuration::deleteByName('ZPRO_NO_RATED_MSG')
			OR !Configuration::deleteByName('ZPRO_NUMBER')
			OR !Configuration::deleteByName('ZPRO_PATH')
			OR !Configuration::deleteByName('ZPRO_ICON_RANGE')
			OR !Configuration::deleteByName('ZPRO_STAR_HALF')
			OR !Configuration::deleteByName('ZPRO_STAR_OFF')
			OR !Configuration::deleteByName('ZPRO_STAR_ON')
			OR !Configuration::deleteByName('ZPRO_START'))
				return false;
		/*Delete Configuration value*/
		if (!Configuration::deleteByName('ZPRO_ENABLE_EMAIL') 
		 	OR !Configuration::deleteByName('ZPRO_ENABLE_WEBSITE') 
		 	OR !Configuration::deleteByName('ZPRO_DISPLAY_EMAIL')
		 	OR !Configuration::deleteByName('ZPRO_DISPLAY_WEBSITE')
		 	OR !Configuration::deleteByName('ZPRO_DISPLAY_TITLE'))
				return false;
		/*Delete Configuration value*/
		if (!Configuration::deleteByName('ZPRO_ENABLE_CAPTCHA') 
			OR !Configuration::deleteByName('ZPRO_HEIGHT_IMG') 
		 	OR !Configuration::deleteByName('ZPRO_WIDTH_IMG') 
		 	OR !Configuration::deleteByName('ZPRO_BG_COLOR')
		 	OR !Configuration::deleteByName('ZPRO_TEXT_COLOR')
		 	OR !Configuration::deleteByName('ZPRO_LINE_COLOR')
		 	OR !Configuration::deleteByName('ZPRO_CODE_LENGTH') 
		 	OR !Configuration::deleteByName('ZPRO_NUMBER_LINE')
		 	OR !Configuration::deleteByName('ZPRO_SIGNATURE_TEXT')
		 	OR !Configuration::deleteByName('ZPRO_SIGNATURE_COLOR'))
				return false;
		/*Delete Configuration value*/
		if (!Configuration::deleteByName('ZPRO_ENABLE_EMAIL_NOTIFICATION') 
		 	OR !Configuration::deleteByName('ZPRO_EMAIL_NOTIFICATION') 
		 	OR !Configuration::deleteByName('ZPRO_EMAIL_SUBJECT')
		 	OR !Configuration::deleteByName('ZPRO_EMAIL_TEMPLATE'))
				return false;
		if (!Db::getInstance()->Execute('DROP TABLE `'._DB_PREFIX_.'zproduct_review`')
		 OR !Db::getInstance()->Execute('DROP TABLE `'._DB_PREFIX_.'zproduct_rating`')
		 OR !Db::getInstance()->Execute('DROP TABLE `'._DB_PREFIX_.'zproduct_criterion_product`')
		 OR !Db::getInstance()->Execute('DROP TABLE `'._DB_PREFIX_.'zproduct_criterion_lang`')
		 OR !Db::getInstance()->Execute('DROP TABLE `'._DB_PREFIX_.'zproduct_criterion_category`')
		 OR !Db::getInstance()->Execute('DROP TABLE `'._DB_PREFIX_.'zalias_custommers`')
		 OR !Db::getInstance()->Execute('DROP TABLE `'._DB_PREFIX_.'zcustomer_badges`')
		 OR !Db::getInstance()->Execute('DROP TABLE `'._DB_PREFIX_.'zcustomer_badges_lang`')
		 OR !Db::getInstance()->Execute('DROP TABLE `'._DB_PREFIX_.'zproduct_criterion`'))
			return false;
		/*Core UnInstall*/
		
		return true;
	}
	
	/**
	 * Remove tab in administration
	 * 
	 * @return boolean
	 */
	private function _removeAdminTab()
	{
		$idTab = Tab::getIdFromClassName('AdminZProductReviewRating');
		$tab = new Tab($idTab);
		if (!$tab->delete())
      		return false;
		return true;
	}
}
?>